package com.leyou.cart.listener;

import com.leyou.cart.pojo.Cart;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * Created by HuangGuojun on 2018/8/20.
 */
@Component
public class MqListener {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private  static final  String  KEY_PREFIX = "ly:cart:uid:";

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "leyou.order.cart.queue", durable = "true"),
            exchange = @Exchange(value = "leyou.order.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC
            ),
            key = {"order.cart"}
    ))
    public void listenOrderMessage(Map<Long, List<Long>> orderMassage) {
        String  key =  null  ;
        for (Long along : orderMassage.keySet()) {
            key  = KEY_PREFIX + along ;
        }
        List<Long> skuIds = null;
        for (List<Long> list : orderMassage.values()) {
            skuIds = list ;
        }

        // 获取hash操作对象
        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        // 获取购物车数据
        for (Long skuId : skuIds) {
           hashOps.delete(skuId.toString());
        }
    }
}
